<template>
  <div class="app-container">
    <el-card class="mb20">
      <el-form :model="list_q" ref="list_q_ref" inline>
        <el-form-item
          v-for="(
            { form_item_prop: { label, prop }, component_name, component_prop },
            index
          ) in list_q_c"
          :key="index"
          v-bind="{ label, prop }"
        >
          <component
            :is="component_name"
            v-model="list_q[prop]"
            v-bind="component_prop"
            :placeholder="label"
          >
            <template v-if="component_name == 'el-select'">
              <el-option
                v-for="i in component_prop.option_data"
                :key="i.id"
                :value="i[component_prop.option_prop.value]"
                :label="i[component_prop.option_prop.label]"
              ></el-option>
            </template>
          </component>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="get_list">搜索</el-button>
          <el-button @click="reset_list_q">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button type="success" @click="open_add_dialog" plain>新增</el-button>
      <el-button
        :disabled="del_rows.length == 0"
        type="danger"
        plain
        @click="del_row(true)"
        >删除</el-button
      >
      <el-table :data="list" @selection-change="(val) => (del_rows = val)">
        <el-table-column type="selection"></el-table-column>
        <el-table-column
          v-for="item in list_c"
          :key="item.prop"
          v-bind="item"
        ></el-table-column>
        <el-table-column width="200px" label="操作" v-slot="{ row }">
          <el-button type="primary" size="mini" @click="open_edit_dialog(row)"
            >修改</el-button
          >
          <el-button type="danger" size="mini" @click="del_row(false, row)"
            >删除</el-button
          >
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="
          (val) => {
            pager.limit = val;
            get_list();
          }
        "
        @current-change="
          (val) => {
            pager.page = val;
            get_list();
          }
        "
        :current-page="pager.page"
        :page-sizes="[2, 10, 20, 30]"
        :page-size="pager.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pager.total"
        style="text-align: right; margin-top: 20px"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      :title="title"
      :visible.sync="visible"
      @close="reset_list_e"
      center
      width="1500px"
    >
      <el-form :model="list_e" ref="list_e_ref" inline>
        <el-form-item
          v-for="(
            {
              form_item_prop: { label, prop, required },
              component_name,
              component_prop,
            },
            index
          ) in list_e_c"
          :key="index"
          v-bind="{ label, prop, required }"
          v-show="is_add || !(!is_add && component_prop.is_add)"
        >
          <component
            :is="component_name"
            v-model="list_e[prop]"
            v-bind="component_prop"
            :placeholder="label"
          >
            <template v-if="label == '客户名称'">
              <el-button slot="append" @click="open_customer_dialog"
                >选择</el-button
              >
            </template>
          </component>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <el-button type="success" @click="add_detail_row(true)">添加</el-button>
      <el-table :data="detailList">
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column width="200px" label="产品" v-slot="{ row }">
          <span>{{ row.material.name }}</span>
          <el-button
            style="margin-left: 20px"
            type="primary"
            size="mini"
            @click="open_material_dialog(row.id)"
            >选择</el-button
          >
        </el-table-column>
        <el-table-column
          v-for="item in list_detailList_c"
          :key="item.prop"
          v-bind="item"
          width="140px"
        >
          <template v-if="item.cn" #default="{ row }">
            <component :is="item.cn" v-bind="item" v-model="row[item.prop]" />
          </template>
          <template v-else-if="item.label == '金额'" #default="{ row }">
            <span>{{ (row.amount = row.price * row.quantity) }}</span>
          </template>
        </el-table-column>
        <el-table-column width="200px" label="操作" v-slot="{ $index }">
          <el-button
            type="success"
            size="mini"
            @click="add_detail_row(false, $index)"
            >添加</el-button
          >
          <el-button type="danger" size="mini" @click="del_detail_row($index)"
            >删除</el-button
          >
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog :visible.sync="visible_customer" title="选择销售客户" center>
      <el-card class="mb20">
        <el-form :model="list_order_q" ref="list_order_q_ref" inline>
          <el-form-item label="客户名称" prop="name">
            <el-select v-model="list_order_q.name" placeholder="客户名称">
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :value="item.name"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联系人" prop="contact">
            <el-input
              v-model="list_order_q.contact"
              placeholder="联系人"
            ></el-input>
          </el-form-item>
          <el-form-item label="客户分类" prop="category">
            <el-select v-model="list_order_q.category" placeholder="客户分类">
              <el-option value="核心客户" label="核心客户"></el-option>
              <el-option value="普通客户" label="普通客户"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="get_contract_list"
              >搜索</el-button
            >
            <el-button @click="reset_list_order_q">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card>
        <el-table :data="list_order">
          <el-table-column
            v-for="item in list_order_c"
            :key="item.prop"
            v-bind="item"
          ></el-table-column>
          <el-table-column width="200px" label="操作" v-slot="{ row }">
            <el-button type="primary" size="mini" @click="select_customer(row)"
              >选择</el-button
            >
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="
            (val) => {
              pager_order.limit = val;
              get_contract_list();
            }
          "
          @current-change="
            (val) => {
              pager_order.page = val;
              get_contract_list();
            }
          "
          :current-page="pager_order.page"
          :page-sizes="[2, 10, 20, 30]"
          :page-size="pager_order.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pager_order.total"
          style="text-align: right; margin-top: 20px"
        >
        </el-pagination>
      </el-card>
    </el-dialog>
    <el-dialog
      width="1400px"
      :visible.sync="visible_material"
      title="选择物料档案"
      center
    >
      <el-row>
        <el-col :span="6">
          <el-tree
            :data="list_material_category"
            :props="{ value: 'id', label: 'name' }"
            :expand-on-click-node="false"
            @node-click="(val) => get_material_list(val.id)"
            :default-expand-all="true"
          ></el-tree>
        </el-col>
        <el-col :span="18">
          <el-table :data="list_material">
            <el-table-column
              v-for="item in list_material_c"
              :key="item.prop"
              v-bind="item"
            ></el-table-column>
            <el-table-column width="200px" label="操作" v-slot="{ row }">
              <el-button
                type="primary"
                size="mini"
                @click="select_material(row)"
                >选择</el-button
              >
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getSaleContractList, getSalesManList, EditSaleContract, AddSaleContract, DelSaleContract } from '@/api_zc/scm/sale-management/sale-contract'
import { getMaterialCatgoryChildrenList } from '@/api_zc/wms/material-category'

import { getCustomerList as getCustomerList2 } from '@/api_zc/task/sale-order-approve'
import { getSaleOrderList, getSaleOrderDetailList, getCustomerList, editSaleOrder, delSaleOrder, addSaleOrder, getApplyApproveUserList } from '@/api_zc/scm/sale-management/sale-order'
import { getMaterialCategoryList, getMaterialList } from '@/api_zc/mes/product-modeling'
import config_mixin from './config'
import cloneDeep from 'lodash/cloneDeep'
export default {
  mixins: [config_mixin],
  mounted () {
    this.get_list()
    this.get_unity_list()
    this.get_contract_list()
    this.get_material_list()
  },
  data () {
    return {
      list: [],
      visible: false,
      title: '',
      is_add: false,
      visible_customer: false,
      list_order: [],
      detailList: [],
      customerList: [],
      list_material: [],
      list_material_category: [],
      visible_material: false,
      id: 0,
      del_rows: []
    }
  },
  methods: {
    async get_material_list (pid = 0) {
      const { data: { content } } = await getMaterialList({ pid })
      this.list_material = content
    },
    async get_contract_list () {
      const { data: { content, total } } = await getCustomerList({ ...this.list_order_q, ...this.pager_order })
      this.pager_order.total = total
      this.list_order = content
    },
    async get_unity_list () {
      const data2 = await getCustomerList2()
      this.list_q_c.find(item => item.form_item_prop.label == '客户名称').component_prop.option_data = data2.data.content
      this.customerList = data2.data.content
      const data3 = await getApplyApproveUserList()
      this.list_q_c.find(item => item.form_item_prop.label == '申请人').component_prop.option_data = data3.data
      this.list_q_c.find(item => item.form_item_prop.label == '审核人').component_prop.option_data = data3.data
      const { data } = await getMaterialCatgoryChildrenList()
      this.list_material_category = data
    },
    async get_list () {
      if (!this.list_q.deliveryAttr) {
        return
      }
      if (!this.list_q.applyAttr) {
        return
      }
      if (!this.list_q.approveAttr) {
        return
      }
      [this.list_q.deliveryStartDate, this.list_q.deliveryEndDate] = this.list_q.deliveryAttr;
      [this.list_q.applyStartDate, this.list_q.applyEndDate] = this.list_q.applyAttr;
      [this.list_q.approveStartDate, this.list_q.approveEndDate] = this.list_q.approveAttr
      const { data: { total, content } } = await getSaleOrderList({ ...this.list_q, ... this.pager })
      this.list = content
      this.pager.total = total
    },
    reset_list_q () {
      this.$refs.list_q_ref.resetFields()
      this.get_list()
    },
    reset_list_order_q () {
      this.$refs.list_order_q_ref.resetFields()
      this.get_contract_list()
    },
    reset_list_e () {
      this.$refs.list_e_ref.resetFields()
      this.detailList = []
    },
    open_edit_dialog (row) {
      this.visible = true
      this.$nextTick(async () => {
        Object.assign(this.list_e, {
          id: row.id,
          customerId: row.customer.id,
          customerName: row.customer.name,
          remark: row.remark
        })
        const data = await getSaleOrderDetailList({ id: row.id })
        this.detailList = data.data
      })
      this.title = '修改销售订单'
      this.is_add = false
    },
    open_add_dialog () {
      this.visible = true
      this.title = '添加销售订单'
      this.is_add = true
    },
    del_row (flag, row) {
      let text, ids
      if (flag) {
        text = this.del_rows.map(item => item.id).join(',')
        ids = this.del_rows.map(item => item.id)
      } else {
        text = row.id
        ids = [row.id]
      }
      this.$confirm(`是否确认删除销售合同编号为${text}的数据项？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await delSaleOrder({ ids })
        this.$message.success('删除成功')
        this.get_list()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    open_customer_dialog () {
      this.visible_customer = true
    },
    select_customer (row) {
      this.list_e.customerId = row.id
      this.list_e.customerName = row.name
      this.visible_customer = false
    },
    open_material_dialog (id) {
      this.id = id
      this.visible_material = true
    },
    select_material (row) {
      console.log(row)
      if (typeof row.category == 'object') {
        delete row.category
      }
      this.detailList.find(item => item.id == this.id).material = {
        ...row,
        materialId: row.id
      }
      this.visible_material = false
    },
    del_detail_row (index) {
      this.detailList.splice(index, 1)
    },
    add_detail_row (is_push, index) {
      if (is_push) {
        this.detailList.push({
          id: Math.floor(Math.random() * 10000),
          material: {
            name: '',
            model: '',
            specification: '',
            unit: ''
          },
          price: 0,
          quantity: 0,
          amount: 0,
          remark: ''
        })
        return
      }
      this.detailList.splice(index + 1, 0, {
        id: Math.floor(Math.random() * 10000),
        material: {
          name: '',
          model: '',
          specification: '',
          unit: ''
        },
        price: 0,
        quantity: 0,
        amount: 0,
        remark: ''
      })
    },
    async submit () {
      this.$refs.list_e_ref.validate(async (callback) => {
        if (!callback) {
          return this.$message.error('请完善表单')
        }
        this.detailList = this.detailList.map(item => {
          return {
            ...item,
            materialId: item.material.id
          }
        })
        if (this.is_add) {
          await addSaleOrder({ ...this.list_e, detailList: this.detailList })
          this.$message.success('添加成功')
        } else {
          await editSaleOrder({ ...this.list_e, detailList: this.detailList })
          this.$message.success('修改成功')
        }
        this.visible = false
        this.get_list()
      })
    },
  }
}
</script>